<template>
  <div class="statistics" v-loading="loading">
  <ScaleBox :width="1920"
            :height="1080"
            bgc="transparent"
            :delay="100">

    <el-row :gutter="20" style="margin-top: 16px; padding-left: 18px; padding-right: 28px;">

      <!--<editor-fold desc="当前任务统计">-->
      <el-col :span="8"  style="padding-right: 0px;">
        <div class="chart-box">


          <div class="chart-title">
            <span><i class="iconfont icon-huantu"></i>{{$t('common.CurrentTask')}}</span>
          </div>
          <el-divider style="margin: 0;color: #000000;"/>
          <el-button class="linkButton" type="primary" size="small" icon="Link" @click.stop="jumpAgv">{{$t('common.taskList')}}</el-button>

          <v-chart ref="currentRef" class="chart-container" ></v-chart>

        </div>
      </el-col>
      <!--</editor-fold>-->

      <!--<editor-fold desc="历史任务/报警统计">-->
      <el-col :span="16" style="padding-right: 0px;" >
        <div class="chart-box">
          <div class="chart-title">
            <span class="font-mono "><i class="iconfont icon-duotiaozhexiantu"></i>{{$t('common.HistoricalTasks')}}</span>
            <div class="timeLine">

              <el-button color="#4065e0" plain @click="getToday" size="small"
              >{{$t('common.today')}}
              </el-button
              >
              <el-button color="#4065e0" plain @click="getWeek" size="small"
              >{{$t('agv.sevenDaysAgo')}}
              </el-button
              >
              <el-button color="#4065e0" plain @click="getMonth" size="small"
              >{{$t('agv.thirtyDaysAgo')}}
              </el-button
              >

              <div class="timer">
                <el-date-picker
                  v-model="data.pikeTime"
                  type="datetimerange"
                  style="margin-left: 15px"
                  unlink-panels
                  :range-separator="$t('wms.to')"
                  :start-placeholder="$t('wms.startTime')"
                  :end-placeholder="$t('wms.endTime')"
                  clearable
                  size="small"
                  @change="pikeTimeSerch"
                />
              </div>
            </div>
            <el-button-group class="linkButton">
              <el-button type="primary" size="small" icon="Link" @click.stop="jumpAgv">{{$t('common.taskList')}}</el-button>
              <el-button type="primary" size="small" icon="Link" @click.stop="jumpToList('/agvAlarmHistory')">{{$t('common.AlarmList')}}</el-button>
            </el-button-group>
          </div>
          <el-divider style="margin: 0;color: #000000;"/>
          <el-row style="height: 460px">
            <el-col :span="8">
              <div class="text-container-box">
                <div class="text-container">
                  <div class="text-box-num text-box-one">
                    <i class="iconfont icon-jilun"></i>
                    <span class="num">{{data.taskTotalCount}}</span>
                    <el-link type="primary" @click="jumpAgv">{{$t('common.TotalTasks')}}</el-link>
<!--                    <span class="text font-black">任务总数</span>-->
                  </div>
                  <div class="text-box-num text-box-tow">
                    <i class="iconfont icon-fengxianyujing"></i>
                    <span class="num">{{data.warningCount}}</span>
<!--                    <span class="text font-black">报警总数</span>-->
                    <el-link type="primary" @click="jumpToList('/agvAlarmHistory')">{{$t('common.TotalAlarm')}}</el-link>
                  </div>
                </div>
                <div class="text-container">
                  <div class="text-box-num text-box-three">
                    <span class="text font-black" >{{$t('common.tasksWithin30')}}</span>
                    <span class="num">{{data.taskTotalCount30}}</span>
                    <el-link type="primary" @click="jumpAgv">{{$t('common.TotalTasks')}}
                      <i v-if="data.taskTotalCount30Status == 1" class="iconfont icon-shangsheng"></i>
                      <i v-if="data.taskTotalCount30Status == 0" class="iconfont icon-chiping"></i>
                      <i v-if="data.taskTotalCount30Status == -1" class="iconfont icon-xiajiang"></i></el-link>
<!--                    <span class="text font-black">任务总数 <i class="iconfont icon-shangsheng"></i> </span>-->
                  </div>
                  <div class="text-box-num text-box-four">
                    <span class="text font-black">{{$t('common.AlarmWithin30')}}</span>
                    <span class="num">{{data.warningCount30}}</span>
                    <el-link class="px-2.5" type="primary" @click="jumpToList('/agvAlarmHistory')">{{$t('common.comparedTo')}}
                      <i v-if="data.warningCount30Status == 1" class="iconfont icon-shangsheng"></i>
                      <i v-if="data.warningCount30Status == 0" class="iconfont icon-chiping"></i>
                      <i v-if="data.warningCount30Status == -1" class="iconfont icon-xiajiang"></i></el-link>
<!--                    <span class="text font-black">同比上30天  <i class="iconfont icon-xiajiang"></i></span>-->
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="16" class="">
              <v-chart ref="currentRef3" class="chart-container"></v-chart>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <!--</editor-fold>-->

    </el-row>
    <el-row :gutter="20" style="padding-left: 18px; padding-right: 28px;">
      <!--<editor-fold desc="GV数量统计">-->
      <el-col :span="8" style="padding-right: 0px;">
        <div class="chart-box">
          <div class="chart-title">
            <span><i :class="['iconfont', isShowLeft ? 'icon-hengxiangzhuzhuangtu' : 'icon-huantu']"></i>{{$t('common.agvQuantity')}}</span>
            <el-button-group>
              <el-button type="primary" color="#626aef"  plain :class="isShowLeft ? 'inactive-button' : 'active-button'" size="small" @click="chartChange(0)">Pie</el-button>
              <el-button type="primary" color="#626aef"  plain  :class="isShowLeft ? 'active-button' : 'inactive-button'"  size="small" @click="chartChange(1)">
                Category<ArrowRight/>
              </el-button>
            </el-button-group>

              <el-button class="linkButton" type="primary" size="small" icon="Link" @click.stop="jumpToList('/agvDetails')">{{$t('common.DetailedList')}}</el-button>


          </div>
          <el-divider style="margin: 0;color: #000000;"/>
          <v-chart  ref="currentRef4" class="chart-container"></v-chart>


        </div>
      </el-col>
      <!--</editor-fold>-->

      <!--<editor-fold desc="报警等级数据">-->
      <el-col :span="8" style="padding-right: 0px;">
        <div class="chart-box" style="padding-top: 12px">
          <div class="chart-title">
            <span style="padding-top: 2px"><i class="iconfont icon-shuxiangzhuzhuangtu"></i>{{$t('common.AlarmLevelData')}}</span>
            <el-select v-model="data.level" style="margin-left: 15px;width: 120px" clearable :placeholder="$t('wms.pleaseSelect')"  size="small" @change="serch">
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="data.time"
              type="datetimerange"
              style="margin-left: 15px;width: 20px;"
              unlink-panels
              :range-separator="$t('wms.to')"
              :start-placeholder="$t('wms.startTime')"
              :end-placeholder="$t('wms.endTime')"
              clearable
              size="small"
              @change="serch"
            />
          </div>
          <el-button class="linkButton" type="primary" size="small" icon="Link" @click.stop="jumpToList('/agvAlarmHistory')">{{$t('common.DetailedList')}}</el-button>
          <el-divider style="margin: 0;color: #000000;"/>
          <v-chart ref="currentRef5" class="chart-container"></v-chart>
        </div>
      </el-col>
      <!--</editor-fold>-->

      <!--<editor-fold desc="电量区间分布">-->
      <el-col :span="8" style="padding-right: 0px;">
        <div class="chart-box">
          <div class="chart-title">
            <span><i class="iconfont icon-bingtu"></i>{{$t('common.Electricity')}}</span>
          </div>
<!--          <el-button class="linkButton" type="primary" size="small" icon="Link" @click.stop="jumpToList('/statisticsList',1)">明细列表</el-button>-->
          <el-divider style="margin: 0;color: #000000;"/>
          <v-chart ref="currentRef6" class="chart-container"></v-chart>
        </div>
      </el-col>
      <!--</editor-fold>-->
    </el-row>

  </ScaleBox>
  </div>
</template>
<script setup>
import '@/style/tailwind.css'
import ScaleBox from 'vue3-scale-box'
import '@/assets/font/iconfont.css'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import moment from 'moment/moment'
import { renderOption, renderOption3, renderOption4, renderOption5, renderOption6, renderOption7 } from './chart.js'
import { getTaskTotal,getAgvStatus,getAgvBattery,getTaskWarnCount,getTaskWaring} from "@/api/statisticsApi"
import useI18n from '@/hooks/language'

const { t } = useI18n()

const options = ref([
  { label: 'L01', value: 1 },
  { label: 'L02', value: 2 },
  { label: 'L03', value: 3 },
  { label: 'L04', value: 4 },
  { label: 'L05', value: 5 },
  { label: 'L06', value: 6 },
  { label: 'L07', value: 7 },
  { label: 'L08', value: 8 },
  { label: 'L09', value: 9 },
  { label: 'M10', value: 10 },
  { label: 'M11', value: 11 },
  { label: 'M12', value: 12 },
  { label: 'M13', value: 13 }
]);
// 图表的配置
//当前任务统计
const currentRef = ref(null);
const taskStatisticsDate = ref([]);
const taskStatisticsTotal = ref([]);
const router = useRouter();
const loading = ref(false);
//历史任务/报警统计
const currentRef3 = ref(null);
const historicalMissionDate = ref([]);

//AGV数量统计
const currentRef4 = ref(null);
const currentRef7 = ref(null);
const isShowLeft = ref(true)
const avgQuantityDate = ref([]);
const avgQuantityDate2 = ref([]);
const data = reactive({
  level:1,
  time:[],
  pikeTime:[],
  taskTotalCount:0, //	任务总数
  warningCount:0,   //	报警总数
  taskTotalCount30:0, //	30天内任务数据
  warningCount30:0 , //	30 天内报警数
  taskTotalCount30Status:0,	//任务数较上30天 0 代表持平 -1 代表下降 1 代表上升
  warningCount30Status:0, //	报警数较上30天 0 代表持平 -1 代表下降 1 代表上升
})
const chartChange = (flage) =>{
  isShowLeft.value= flage ? true : false
  // 清理图表
  currentRef4.value.clear();

  // 设置新图表选项
  if (flage) {
    currentRef4.value.setOption(renderOption4(avgQuantityDate.value));
  } else {
    currentRef4.value.setOption(renderOption7(avgQuantityDate2.value));
  }
}

//报警等级数据
const currentRef5= ref(null);
const alarmLevelData = ref([]);


//电量区间分布
const currentRef6 = ref(null);
const electricityDate =  ref([]);


//获取数据
//当前任务统计
const getChertDateOne = async()=>{
  try {
    let res = await getTaskTotal()
    taskStatisticsDate.value = [
      {value: res.result.executing, name: t('agv.inExecution'), itemStyle: { color: '#409eff' }},
      {value: res.result.waitExecute, name: t('common.PendingExecution'), itemStyle: { color: '#ffc446' }},
    ]
    taskStatisticsTotal.value = res.result.total
  } catch (error) {
    console.log(error)
  }
}
//历史任务/报警统计
const getChertDateTow= async()=>{
  try {
    let res = await getTaskWaring({
      beginTime:moment(data.pikeTime?.[0]).format('YYYY-MM-DD HH:mm:ss')||'',
      endTime:moment(data.pikeTime?.[1]).format('YYYY-MM-DD HH:mm:ss')||''
    })
    data.taskTotalCount = res.result.taskTotalCount
    data.warningCount = res.result.warningCount
    data.taskTotalCount30 = res.result.taskTotalCount30
    data.warningCount30 = res.result.warningCount30
    data.taskTotalCount30Status = res.result.taskTotalCount30Status
    data.warningCount30Status = res.result.warningCount30Status
    historicalMissionDate.value = res.result.details
  } catch (error) {
    console.log(error)
  }
}
const pikeTimeSerch =async()=>{
  await getChertDateTow()
  currentRef3.value.setOption(renderOption3(historicalMissionDate.value));
}
//AGV数量统计
const getChertDateThree= async()=>{
  try {
    let res = await getAgvStatus()
    avgQuantityDate.value = [res.result.freeCount,res.result.runCount,res.result.warnCount,res.result.chargeCount, res.result.offLineCount ]
      avgQuantityDate2.value = [
      { value: res.result.offLineCount, name: t('common.Offline') },
      { value: res.result.chargeCount, name: t('common.Charging') },
      { value: res.result.warnCount, name:  t('ems.breakdown')},
      { value: res.result.runCount, name: t('ems.operation') },
      { value: res.result.freeCount, name: t('common.idle') },
    ]
  } catch (error) {
    console.log(error)
  }
}
//报警等级数据
const getChertDateFor= async()=>{
  try {
   let res  = await getTaskWarnCount({
     level:data.level,
     beginTime:moment(data.time?.[0]).format('YYYY-MM-DD HH:mm:ss')||'',
     endTime:moment(data.time?.[1]).format('YYYY-MM-DD HH:mm:ss')||''
   })
    alarmLevelData.value = [res.result.oneLevelCount,res.result.twoLevelCount,res.result.threeLevelCount]
  } catch (error) {
    console.log(error)
  }
}

const serch = async() =>{
 await getChertDateFor()
  currentRef5.value.setOption(renderOption5(alarmLevelData.value));
}
//电量区间分布
const getChertDateFiv= async()=>{
  try {
   let res = await getAgvBattery()
    electricityDate.value= [
      { value: res.result.high, name: t('common.Adequate')},
      { value: res.result.moreThanHalf, name: t('common.Medium') },
      { value: res.result.lessThanHalf, name: t('common.Lower')},
      { value: res.result.low, name: t('common.Extremelylow')},
    ]
  } catch (error) {
    console.log(error)
  }
}

onMounted(async() => {
  loading.value = true
  setDefaultPikeTime()
  await getChertDateOne()
  await getChertDateThree()
  await getChertDateFiv()
  await getChertDateFor()
  await getChertDateTow()
  currentRef.value.setOption(renderOption(taskStatisticsDate.value,taskStatisticsTotal.value));
  currentRef3.value.setOption(renderOption3(historicalMissionDate.value));
  currentRef4.value.setOption(renderOption4(avgQuantityDate.value));
  currentRef5.value.setOption(renderOption5(alarmLevelData.value));
  currentRef6.value.setOption(renderOption6(electricityDate.value));
  chartChange(1)
  loading.value = false
});
const getYMDHMS = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 查看今天
const getToday = () => {
  // 确保 pikeTime 是一个数组
  if (!Array.isArray(data.pikeTime)) {
    data.pikeTime = [];
  }
  const today = new Date();
  data.pikeTime[0] = getYMDHMS(today); // 开始时间为今天
  data.pikeTime[1] = getYMDHMS(today); // 结束时间为今天
  pikeTimeSerch();
};

const getWeek = () => {
  // 确保 pikeTime 是一个数组
  if (!Array.isArray(data.pikeTime)) {
    data.pikeTime = [];
  }
  const today = new Date();
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(today.getDate() - 7); // 设置为七天前
  data.pikeTime[0] = getYMDHMS(sevenDaysAgo); // 开始时间为七天前
  data.pikeTime[1] = getYMDHMS(today); // 结束时间为今天
  pikeTimeSerch();
};

const getMonth = () => {
  // 确保 pikeTime 是一个数组
  if (!Array.isArray(data.pikeTime)) {
    data.pikeTime = [];
  }
  const today = new Date();
  const thirtyDaysAgo = new Date(today);
  thirtyDaysAgo.setDate(today.getDate() - 30); // 设置为三十天前
  data.pikeTime[0] = getYMDHMS(thirtyDaysAgo); // 开始时间为三十天前
  data.pikeTime[1] = getYMDHMS(today); // 结束时间为今天
  pikeTimeSerch();
};
// 设置默认值为近七天
const setDefaultPikeTime = () => {
  const today = new Date();
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(today.getDate() - 7); // 设置为七天前

  data.pikeTime[0] = getYMDHMS(sevenDaysAgo); // 开始时间
  data.pikeTime[1] = getYMDHMS(today); // 结束时间

  data.time[0] = getYMDHMS(sevenDaysAgo); // 开始时间
  data.time[1] = getYMDHMS(today); // 结束时间
};

const jumpAgv = () =>{
  router.push('/agv'); // 路由跳转
}
const jumpToList = (value,num) =>{
    router.push({
      path:value,
      query:{
        tabname:num
      }
    });
}
</script>

<style lang="scss" scoped>
@forward "index";
.chart-box{
  position: relative;
  z-index: 1; /* 更高的 z-index */
}
.linkButton{
  position: absolute;
  right: 14px;
  top: 61px;
  z-index: 10; /* 设置一个更高的 z-index */
}

</style>
